package servcie;

import dao.StudentDao;
import domain.StudentDomain;

import java.util.Scanner;

public class StudentService {
    //1、创建StudentDao（库管）
 private    StudentDao studentDao=new StudentDao();
 private  StudentDomain[] studentDomain=  studentDao.findAllStudent();
 private Scanner scanner=new Scanner(System.in);
    public boolean addStudent(StudentDomain stu) {

        //2、将学生对象，传递给StudentDao 库管中的addStudent方法
        //3、将返回的boolean类型结果，返还给StudentController
      return   studentDao.addStudent(stu);
    }

    public boolean isExists(String id) {
      //假设id在数组中不存在
        boolean exists=false;
        for (int i = 0; i < studentDomain.length; i++) {
            StudentDomain studentDomain1=studentDomain[i];
            if(studentDomain1!=null&&studentDomain1.getId().equals(id)){
                exists=true;
                break;
            }
        }
        return exists;
    }

    public boolean deletStudent(String id) {
      boolean flag= studentDao.deletStudent(id);
      if (flag) return true;
      else return false;
    }

    public StudentDomain[] findAll() {
        //调用库管对象的findAllStudent获取学生对象数组
        StudentDomain[] stu=studentDao.findAllStudent();
        //判断数组中是否有学生信息，有：返回地址，没有：返回null
        //思路：数组中只要存在一个不是null的元素，那就代表有学生信息
        boolean flag=false;

        for (int i = 0; i < stu.length; i++) {
            StudentDomain std=stu[i];
            if(std!=null){
                flag=true;
                break;
            }
        }
     if(flag){
         return  stu;
     }
     else return null;
    }

    public boolean changeStudent(String id) {
        int index = studentDao.index(id);
        StudentDomain[] allStudent = studentDao.findAllStudent();
        System.out.println("请输入修改后的姓名：");
        String name=scanner.next();
        allStudent[index].setName(name);
        System.out.println("请输入修改后的年龄：");
        int age=scanner.nextInt();
        allStudent[index].setAge(age);
        if(name.equals(allStudent[index].getName())||name==null)return true;
        else return false;
    }
}
